<?php
namespace app\system\controller;

use app\common\model\Business;
use app\common\model\Rec;
use think\Db;
use app\common\model\Logs;
use app\common\model\Account;

use app\common\model\User as U;


class User extends Common
{
    protected $pageSize = 20;

    /**
     * 用户列表
     * @param string $keywords
     * @param int $type
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index($keywords='', $type=-1, $pid=0, $shop_id=0)
    {
        $keywords = trim($keywords);
        $str = '?';
        $where = [];
        if (!empty($keywords)) {
            $where['tel|name'] = ['like', "%$keywords%"];
            $str .= 'keywords='.$keywords;
        }
        if ($type != -1) {
            $where['user_type'] = $type;
            $str .= $str != '?' ? '&' : '';
            $str .= 'type='.$type;
        }
        if ($pid > 0) {
            $where['pid'] = $pid;
            $str .= $str != '?' ? '&' : '';
            $str .= 'pid='.$pid;
        }
        if ($shop_id > 0) {
            $where['shop_id'] = $shop_id;
            $str .= $str != '?' ? '&' : '';
            $str .= 'shop_id='.$shop_id;
        }
        $pageconfig['path'] = url($str);

        $userModel = new \app\common\model\User();
        $list = $userModel->selectUser($where, $this->pageSize, $pageconfig);
        foreach ($list as &$v) {
            if ($v['pid'] > 0) {
                $p_user = $userModel->where(['id'=>$v['referee_id']])->field('name,tel')->find();
                $v['p_user'] = "{$p_user['name']}";
            }
            $v['l_title'] = db('level_think')->where(['id'=>$v['user_type']])->value('title');
            if ($v['user_type'] > 0) {
                $v['has_son'] = $userModel->where(['pid'=>$v['id'],'is_active'=>1])->count();
            } else {
                $v['has_son'] = 0;
            }
        }

        $assign = [
            'list' => $list,
            'typeList' => $this->typeList
        ];
        return $this->fetch($pid > 0 ? 'sons' : 'index', $assign);
    }

    /**
     * 添加编辑用户
     * @param int $id
     * @return mixed|\think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function save($id=0) {
        $userModel = new \app\common\model\User();
        if (isAjaxPost()) {
            Db::startTrans();
            $data = input('post.');
            $validate = new \app\system\validate\User();
            if (!$validate->check($data, '', $id > 0 ? 'edit' : 'add')) {
                return $this->jsonError($validate->getError());
            }
           
            unset($data['id']);
            if ($id > 0) {
                $is = $userModel->where(['tel' => $data['tel'],'id'=>['neq',$data['id']]])->find();
                if ($is) {
                    return $this->jsonError('手机号已存在');
                }
                if ($userModel->update($data, ['id'=>$id]) !== false) {
                    Db::commit();
                    return $this->jsonSuccess('修改成功');
                } else {
                    return $this->jsonError('修改失败');
                }
            } else {
                $parent = $userModel->where(['code' => $data['referee_code'], 'is_active' => 1])->field('id,code,name')->find();
                if (empty($parent)) {
                    return $this->jsonError('推荐人不存在');
                }
                $is = $userModel->where(['tel' => $data['tel']])->field('id,code,name')->find();
                if ($is) {
                    return $this->jsonError('手机号已存在');
                }
                $data['add_time'] = time();
                $data['referee_id'] = $parent['id'];
                $data['pid'] = $parent['id'];

                $data['img'] = config('default_user_img');
                $data['password'] = md5('111111');
                $data['pay_password'] = md5('222222');
                if ($uid = $userModel->insertGetId($data)) {
                    $code = generate(6);
                    $userModel->where(['id'=>$uid])->setField('code', $code);
                    $data['id'] = $uid;
                    $data['code'] = $code;
                    //生成邀请二维码
                    saveQrcode($data);
                    //记录推荐关系
                    $res = Rec::recommend($uid, $code, $data['referee_code']);
                    if ($res !== true) {
                        Db::rollback();
                        return $this->jsonError('加载失败');;
                    }
                   Db::commit();
                    return $this->jsonSuccess('添加成功');
                } else {
                    return $this->jsonError('添加失败');
                }
            }
        }
        if ($id > 0) {
            $this->assign('data', $userModel->findUser(['id'=>$id]));
        }
        $this->assign('level', \app\common\model\Level::all());
        $this->assign('puser', $userModel->where(['user_type'=>2, 'id'=>['neq', $id]])->column('id,name,tel', 'id'));
        $this->assign('shop_list', db('shop')->select());

        return $this->fetch();
    }

    /**
     * 删除用户
     * @param $id
     * @return \think\response\Json
     */
    public function del($id)
    {
        if (isAjaxPost()) {
            $id = intval($id);
            if ($id <= 0) {
                return $this->jsonError('删除失败');
            }
            $model = new \app\common\model\User();
            $is=$model::get(['referee_id'=>$id]);
            $order=db('order')->where(['uid'=>$id])->find();
            if($is || $id==1 ||  $order){
                return $this->jsonError('不可删除');
            }
            if ($model->where(['id'=>$id])->delete() !== false) {
                @unlink("./qrcode/invite/{$id}.png");
                //删除推荐关系
                db('member_rec')->where(['new_member_id'=>$id])->delete();
                Logs::adds('删除会员id'.$id,$this->admin['id'], $this->admin['username']);
                return $this->jsonSuccess('删除成功');
            } else {
                return $this->jsonError('删除失败');
            }
        }
    }

    /**
     * 批量删除
     * */
    public function delAll()
    {
        if (isAjaxPost()) {
            $post = input('post.');

            if (empty($post['id']) || !is_array($post['id']) || count($post['id']) <= 0) {
                return $this->jsonError('请勾选需要删除的用户！');
            }
            $ids = $post['id'];

            $model = new \app\common\model\User();
            if ($model->where(['id'=>['in', $ids]])->delete() !== false) {
                foreach ($ids as $v) {
                    @unlink("./qrcode/invite/{$v}.png");
                }
                return $this->jsonSuccess('删除成功');
            } else {
                return $this->jsonError('删除失败');
            }
        }
    }

    public function locks($id, $locks)
    {
        if (isAjaxPost()) {
            $id = intval($id);
            $locks = intval($locks);
            if ($id <= 0 || !in_array($locks, [0, 1])) {
                return $this->jsonError('操作失败');
            }

            $manageModel = new \app\common\model\User();
            if ($manageModel->update(['locks' => $locks], ['id' => $id]) !== false) {
                return $this->jsonSuccess('操作成功');
            } else {
                return $this->jsonError('操作失败');
            }
        }
    }

    /**
     * 商家列表
     * @param string $keywords
     * @param int $status
     * @return mixed
     */
    public function business($keywords='', $status=0)
    {
        $keywords = trim($keywords);
        $str = '?';
        $where = [];
        if (!empty($keywords)) {
            $where['title|tel|name'] = ['like', "%$keywords%"];
            $str .= 'keywords='.$keywords;
        }
        if ($status > 0) {
            $where['status'] = $status;
            $str .= $str != '?' ? '&' : '';
            $str .= 'status='.$status;
        }
        $pageconfig['path'] = url($str);

        $userModel = new Business();
        $list = $userModel->getList($where, $this->pageSize, $pageconfig);

        $assign = [
            'list' => $list,
        ];
        return $this->fetch('', $assign);
    }

    /**
     * 删除用户
     * @param $id
     * @return \think\response\Json
     */
    public function business_del($id)
    {
        !isAjaxPost() && die;
        $id = intval($id);
        if ($id <= 0) {
            return $this->jsonError('删除失败');
        }

        $model = new Business();
        if ($model->where(['id'=>$id,'status'=>3])->count() <= 0) {
            return $this->jsonError('删除失败');
        }

        if ($model->where(['id'=>$id])->delete() !== false) {
            return $this->jsonSuccess('删除成功');
        } else {
            return $this->jsonError('删除失败');
        }
    }

    /**
     * 商家审核
     * @param $id
     * @param $state
     * @param string $reason
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function business_examine ($id, $state, $reason='') {
        if (isAjaxPost()) {
            $model = new Business();
            $info = $model->where('id', $id)->find();
            if (empty($info)) {
                return $this->jsonError('信息不存在');
            }
            $info = $info->toArray();
            if ($info['status'] == 1) {
                if ($state == 1) {
                    $data = [
                        'status' => 2,
                    ];
                } elseif ($state == 2) {
                    if (empty($reason)) {
                        return $this->jsonError('请填写拒绝理由');
                    }
                    $data = [
                        'status' => 3,
                        'reason' => $reason,
                    ];
                } else {
                    return $this->jsonError('状态错误');
                }
            } elseif ($info['status'] == 4) {
                if ($state == 1) {
                    $data = [
                        'status' => 2,
                    ];
                } elseif ($state == 2) {
                    if (empty($reason)) {
                        return $this->jsonError('请填写拒绝理由');
                    }
                    $data = [
                        'status' => 5,
                        'reason' => $reason,
                    ];
                } else {
                    return $this->jsonError('状态错误');
                }
            } else {
                return $this->jsonError('状态错误');
            }

            $model->startTrans();
            if ($model->save($data, ['id' => $id]) !== false) {
                if ($state == 1) {
                    //用户类型改为分销商
                    $user_model = new \app\common\model\User();
                    if ($user_model->where(['id'=>$info['user_id']])->setField('user_type', 1) === false) {
                        $model->rollback();
                        return $this->jsonError('操作失败');
                    }
                }
                $model->commit();
                return $this->jsonSuccess('操作成功');
            } else {
                return $this->jsonError('操作失败');
            }
        }
    }
    /**
     * Undocumented function
     *
     * @param Type|null $var
     * @return void
     * @author 阿文
     * @date 2021-11-17 20:50
     */
    public function r_check($id='',$state='')
    {
        Db::startTrans();
        
        

        if (isAjaxPost()) {
            $one=db('renzheng')->find($id);
            if($state==1){
               $update['is_renzheng']=1;
               $update=$one;
               unset($update['uid']);
               unset($update['id']);

               unset($update['ucode']);
               unset($update['state']);
               unset($update['create_time']);
               unset($update['confirm_time']);
               unset($update['admin_id']);
               unset($update['admin_name']);
                db('user')->where(['id'=>$one['uid']])->update($update);
            }
            $res=db('renzheng')->where(['id'=>$id])->update(['state'=>$state,'admin_name'=>$this->admin['username'],'admin_id'=>$this->admin['id'],'confirm_time'=>time()]);
            if(!$res){
                 Db::rollback();
                 return $this->jsonError('操作失败');
            }
            Db::commit(); 
            $type=$state==1?'通过':'驳回';
            Logs::adds($type.'['.$one['ucode'].']的申请',$this->admin['id'], $this->admin['username']);
            return $this->jsonSuccess('操作成功');
        }
        $keywords = input('keywords');
        $where = [];
        if (!empty($keywords)) {
            $where['ucode'] = ['like', "%$keywords%"];
            
        }else{
            $where['ucode'] = ['like', "%%"];

        }
        if (input('state') > 0) {
            $where['state'] = input('state');
        }
       
        $list =  db('renzheng ag')
        ->where($where)->field('ag.*')->paginate(10,false, ['query' => request()->get()]);
        $assign = [
            'list' => $list,
        ];
        return $this->fetch('', $assign);

       
    }
    /**
     * 推荐关系
     *
     * @return void
     * @author 阿文
     * @date 2021-11-18 22:08
     */
    public function recommend()
    {
        try {
            if ($this->request->isAjax()) {
                $id = $this->request->param('id');
                $list = U::where('referee_id', $id)->field('id,code,name,tel')->select();
                foreach ($list as &$v) {
                    $v['title'] = '编号【' . $v['code'] . '】姓名【' . $v['name'] . '】手机号【' . $v['tel'] . '】';
                }
                return json(['code' => 1, 'msg' => 'success', 'result' => $list]);
            }
            $keyword = $this->request->param('keyword');
            if ($keyword) {
                $map['code|name|tel'] = $keyword;
            } else {
                $map['code'] = 'admin';
            }
            $first = U::where($map)->field('id,code,name,tel')->find();
            if ($first) {
                $first['title'] = '编号【' . $first['code'] . '】姓名【' . $first['name'] . '】手机号【' . $first['tel'] . '】';
            }
            $this->assign('first', $first);
            return $this->fetch();

        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }
    }
    public function edit($id = '', $tpl = 'edit')
    {
        try {
            $this->assign([
                'info' => U::find($id),
                // 'assets' => Assets::getFields(3),
                // 'lucky' => \app\common\model\Lucky::all(),
                // 'permit' => \app\common\model\Permit::all(),
                // 'star' => \app\common\model\Star::all()
            ]);
            return $this->fetch($tpl);

        } catch (\Exception $e) {
            return $e->getMessage();
        }

    }
    /**
     * @param $id -- 会员ID+
     * @return \think\response\Json
     * 原点 2021年4月26日11:22:11 充值
     */
    public function recharge($id)
    {
        try {
            
            $param = $this->request->param();
            if ($this->request->isGet()) {
                $res = U::where('id', $id)->value($param['type']);
                return json(['code' => 1, 'result' => $res]);
            }
            if ($this->request->isPost()) {
                if ($param['amount'] <= 0) {
                    return json(['status' => -1, 'message' => '金额错误']);
                }
                if ($param['operation'] == 1) {
                    Account::add($id, $param['type'], $param['amount'], '后台充值', '+', $this->admin['id']);
                    $logs = '后台充值【' . get_pay_way($param['type']) . '】金额【' . $param['amount'] . '】会员【' . $param['code'] . '】';
                } else {
                    Account::add($id, $param['type'], $param['amount'], '后台扣除', '-', $this->admin['id']);
                    $logs = '后台扣除【' . get_pay_way($param['type']) . '】金额【' . $param['amount'] . '】会员【' . $param['code'] . '】';
                }
                Logs::adds($logs, $this->admin['id'], $this->admin['username']);
                return json(['status' => 1, 'message' => $param['operation'] == 1 ? '已充值' : '已扣除']);
            }
            return json(['status' => -1, 'message' => 'error:请求方式错误']);

        } catch (\Exception $e) {
            return json(['status' => -1, 'message' => $e->getMessage()]);
        }

    }
    /**
     * 欢乐视频
     *
     * @return void
     * @author 阿文
     * @date 2021-11-20 20:52
     */
    public function video($id='',$state='')
    {
        if ($this->request->isAjax()) {
            Db::startTrans();
            $info = db('member_sign')->find($id);
            if (empty($info)) $this->jsonError('审核失败');
            if($info['state'] != 0){
                $this->jsonError('此笔记录已审核，请勿重复审核');
            }
            if (empty($info)) return json(['status' => -1, 'message' => '审核失败']);
            if ($state == 1 && $info['state']==0) {
                Account::add($info['uid'], 'bonus2', config('sign_num'), '欢笑视频', '+');
                Logs::adds('审核视频，记录ID【' . $id . '】', $this->admin['id'], $this->admin['username']);
            }
            $update=[
                'admin_id'=>$this->admin['id'],
                'admin_name'=>$this->admin['username'],
                'state'=>$state,
                'confirm_time'=>time(),
            ];
            $res=db('member_sign')->where(['id'=>$id])->update($update);
            Db::commit();
            return $this->jsonSuccess('已审核');
        }
        $keyword = $this->request->param('keyword');
        if ($keyword) {
            $where['ucode|uname'] = ['like','%'.input('keyword').'%'];;
        } else {
            $where['ucode|uname'] = ['like','%%'];;
        }
        $list =  db('member_sign ag')
        ->where($where)->field('ag.*')->paginate(10,false, ['query' => request()->get()]);
        $assign = [
            'list' => $list,
        ];
        return $this->fetch('', $assign);
    }
}